/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Panel.java
 *
 * Created on 9/10/2011, 05:20:01 PM
 */
package scrumsprint1;

import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JButton;
import java.io.*;
import java.net.*;
import java.util.regex.Pattern;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.SwingUtilities;
import javax.swing.JWindow;

/**
 *
 * @author SAGA
 */
public class Panel extends javax.swing.JFrame {
    
    public JButton[][] btnMatrizBotones;
    public claseCasilla[][] matrizCasillas;
    public JButton[][] btnMatrizBotonesOponente;
    public claseCasilla[][] matrizCasillasOponente;
    int intAlto = 0, intAncho = 0, intAnchoBtn = 15, intAltoBtn = 15, intPix = 0;
    public int tipoNave=0;//Esta variable se utiliza para saber que tipo de nave dibujar en el otro form
    public boolean nav1=false,nav2=false,nav3=false,nav4=false;
    public boolean TurnoActual=true;
    
    /** Creates new form Panel */
    public Panel() {
        splash();
        initComponents();
        try{
            setDefaultLookAndFeelDecorated(true);
            JDialog.setDefaultLookAndFeelDecorated( true );
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        }catch(Exception e){}
        SwingUtilities.updateComponentTreeUI( this );
        
        vida = cantidad_naves = 0;
        esServidor = true;
                
        this.setLocationRelativeTo( null );
        
        this.jPanel1.setEnabled(false);
        this.jPanel2.setEnabled(false);
        this.jPanel1.setVisible(false);
        this.jPanel2.setVisible(false);
        this.jLabel3.setVisible( false );
        this.lblTiempo.setVisible( false );
        this.btnListo.setVisible( false );
        
        jw.setVisible( false );
        this.jMenuItem2.setVisible(false);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jdElegirServidor = new javax.swing.JDialog();
        jrbJugadorS = new javax.swing.JRadioButton();
        jrbJugadorC = new javax.swing.JRadioButton();
        btnIniciar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        btnNave1 = new javax.swing.JButton();
        btnNave2 = new javax.swing.JButton();
        btnNave3 = new javax.swing.JButton();
        btnNave4 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        op15 = new javax.swing.JRadioButton();
        op20 = new javax.swing.JRadioButton();
        op25 = new javax.swing.JRadioButton();
        jLabel2 = new javax.swing.JLabel();
        btnCrear = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        lblTiempo = new javax.swing.JLabel();
        lbltab = new javax.swing.JLabel();
        lbltabOp = new javax.swing.JLabel();
        btnListo = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        mnuNuevo = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        mnuSalir = new javax.swing.JMenuItem();

        jdElegirServidor.setTitle("Seleccionar tipo jugador");

        jrbJugadorS.setFont(new java.awt.Font("PakType Naqsh", 3, 14)); // NOI18N
        jrbJugadorS.setSelected(true);
        jrbJugadorS.setText("Jugador Servidor");
        jrbJugadorS.setToolTipText("Crea el tablero y define cantidad de naves");
        jrbJugadorS.setBorderPainted(true);
        jrbJugadorS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/servidor.png"))); // NOI18N
        jrbJugadorS.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbJugadorSActionPerformed(evt);
            }
        });

        jrbJugadorC.setFont(new java.awt.Font("PakType Naqsh", 3, 14)); // NOI18N
        jrbJugadorC.setText("Conectarse a una red");
        jrbJugadorC.setBorderPainted(true);
        jrbJugadorC.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/conectarse.png"))); // NOI18N
        jrbJugadorC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbJugadorCActionPerformed(evt);
            }
        });

        btnIniciar.setFont(new java.awt.Font("PakType Naqsh", 3, 14));
        btnIniciar.setText("¡Iniciar!");
        btnIniciar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIniciarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jdElegirServidorLayout = new javax.swing.GroupLayout(jdElegirServidor.getContentPane());
        jdElegirServidor.getContentPane().setLayout(jdElegirServidorLayout);
        jdElegirServidorLayout.setHorizontalGroup(
            jdElegirServidorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jdElegirServidorLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jdElegirServidorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jrbJugadorC, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE)
                    .addComponent(jrbJugadorS, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
                .addComponent(btnIniciar)
                .addContainerGap())
        );
        jdElegirServidorLayout.setVerticalGroup(
            jdElegirServidorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jdElegirServidorLayout.createSequentialGroup()
                .addGroup(jdElegirServidorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jdElegirServidorLayout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addComponent(jrbJugadorS)
                        .addGap(18, 18, 18)
                        .addComponent(jrbJugadorC))
                    .addGroup(jdElegirServidorLayout.createSequentialGroup()
                        .addGap(51, 51, 51)
                        .addComponent(btnIniciar)))
                .addContainerGap(17, Short.MAX_VALUE))
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Batalla Naval");
        setIconImage(new ImageIcon(getClass().getResource("/images/barco.png")).getImage());
        setMinimumSize(new java.awt.Dimension(350, 400));
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED, new java.awt.Color(153, 153, 153), new java.awt.Color(204, 204, 204), new java.awt.Color(0, 0, 0), new java.awt.Color(102, 102, 102)));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setText("Naves");

        btnNave1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/proyectoanalisis/Naves/nave1icono.jpg"))); // NOI18N
        btnNave1.setEnabled(false);
        btnNave1.setMaximumSize(new java.awt.Dimension(70, 50));
        btnNave1.setMinimumSize(new java.awt.Dimension(70, 50));
        btnNave1.setPreferredSize(new java.awt.Dimension(70, 50));
        btnNave1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNave1ActionPerformed(evt);
            }
        });

        btnNave2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/proyectoanalisis/Naves/nave2icono.jpg"))); // NOI18N
        btnNave2.setEnabled(false);
        btnNave2.setMaximumSize(new java.awt.Dimension(70, 50));
        btnNave2.setMinimumSize(new java.awt.Dimension(70, 50));
        btnNave2.setPreferredSize(new java.awt.Dimension(70, 50));
        btnNave2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNave2ActionPerformed(evt);
            }
        });

        btnNave3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/proyectoanalisis/Naves/nave3icono.jpg"))); // NOI18N
        btnNave3.setEnabled(false);
        btnNave3.setMaximumSize(new java.awt.Dimension(70, 50));
        btnNave3.setMinimumSize(new java.awt.Dimension(70, 50));
        btnNave3.setPreferredSize(new java.awt.Dimension(70, 50));
        btnNave3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNave3ActionPerformed(evt);
            }
        });

        btnNave4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/proyectoanalisis/Naves/nave4icono.jpg"))); // NOI18N
        btnNave4.setEnabled(false);
        btnNave4.setMaximumSize(new java.awt.Dimension(70, 50));
        btnNave4.setMinimumSize(new java.awt.Dimension(70, 50));
        btnNave4.setPreferredSize(new java.awt.Dimension(70, 50));
        btnNave4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNave4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnNave2, 0, 0, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addComponent(btnNave1, javax.swing.GroupLayout.PREFERRED_SIZE, 55, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnNave4, 0, 0, Short.MAX_VALUE)
                    .addComponent(btnNave3, javax.swing.GroupLayout.PREFERRED_SIZE, 51, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnNave3, 0, 0, Short.MAX_VALUE)
                    .addComponent(btnNave1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, Short.MAX_VALUE))
                .addGap(16, 16, 16)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnNave4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnNave2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED, new java.awt.Color(153, 153, 153), new java.awt.Color(204, 204, 204), new java.awt.Color(0, 0, 0), new java.awt.Color(102, 102, 102)));

        buttonGroup1.add(op15);
        op15.setSelected(true);
        op15.setText("15 x 15");

        buttonGroup1.add(op20);
        op20.setText("20 x 20");

        buttonGroup1.add(op25);
        op25.setText("25 x 25");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel2.setText("Tamanio del Tablero");

        btnCrear.setText("Crear");
        btnCrear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCrearActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(op25, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(op15, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(op20, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(btnCrear))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel2)
                .addGap(2, 2, 2)
                .addComponent(op15)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(op20)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(op25)
                .addGap(18, 18, 18)
                .addComponent(btnCrear)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel3.setFont(new java.awt.Font("SansSerif", 0, 15));
        jLabel3.setText("Tiempo de Juego:");

        lblTiempo.setFont(new java.awt.Font("SansSerif", 0, 15));
        lblTiempo.setForeground(java.awt.Color.blue);
        lblTiempo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblTiempo.setText("00:00:000");

        lbltab.setFont(new java.awt.Font("Tahoma", 1, 11));
        lbltab.setText("Tablero");

        lbltabOp.setFont(new java.awt.Font("Tahoma", 1, 11));
        lbltabOp.setText("Tablero Oponente");

        btnListo.setFont(new java.awt.Font("Dialog", 3, 12));
        btnListo.setText("¡Listo!");
        btnListo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnListoActionPerformed(evt);
            }
        });

        jMenu1.setText("File");

        mnuNuevo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        mnuNuevo.setText("Nuevo");
        mnuNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuNuevoActionPerformed(evt);
            }
        });
        jMenu1.add(mnuNuevo);

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem2.setText("Probar Conexion");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        mnuSalir.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
        mnuSalir.setText("Salir");
        mnuSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuSalirActionPerformed(evt);
            }
        });
        jMenu1.add(mnuSalir);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblTiempo, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(462, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(35, 35, 35)
                        .addComponent(lbltab)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 181, Short.MAX_VALUE)
                        .addComponent(lbltabOp)
                        .addGap(61, 61, 61))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
            .addGroup(layout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addComponent(btnListo, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(487, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10)
                        .addComponent(jLabel3)
                        .addGap(10, 10, 10)
                        .addComponent(lblTiempo))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lbltab)
                            .addComponent(lbltabOp))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnListo)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCrearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCrearActionPerformed
        // TODO add your handling code here:


        if (op15.isSelected()) {
            intAlto = 15;
            intAncho = 15;
            intPix = 0;
        } else if (op20.isSelected()) {
            intAlto = 20;
            intAncho = 20;
            intPix = 0;
        } else {
            intAlto = 25;
            intAncho = 25;
            intPix = 0;
        }
        this.setSize(intAncho*intAnchoBtn+200+(intAncho*(intAltoBtn+12)), (intAlto *( intAltoBtn +15)+ 25));
        crearTablero(intAlto, intAncho);
        crearTableroOponente(intAlto, intAncho);
        //Se colaca en false porque solo se puede crear un tablero por turno
        btnCrear.setEnabled(false);
        //Habilitando botones para naves
        btnNave1.setEnabled(true);
        btnNave2.setEnabled(true);
        btnNave3.setEnabled(true);
        btnNave4.setEnabled(true);

        //Codigo para agregar acciones a los botones

        for(int i=0;i<intAlto;i++){
            for(int j=0;j<intAncho;j++){
                btnMatrizBotonesOponente[i][j].setEnabled(true);
        btnMatrizBotonesOponente[i][j].addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MatrizBotonesActionPerformed(evt);
            }
        });
            }
        }

        this.jPanel1.setVisible( true );
        this.jPanel2.setVisible( false );
        
        this.setLocationRelativeTo( null );

    }//GEN-LAST:event_btnCrearActionPerformed

    private void btnNave1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNave1ActionPerformed
        // TODO add your handling code here:
        new GetMovimiento1( this ).setVisible(true);
        //Se desabilita el boton porque solo es 1 tipo de nave por turno
        tipoNave =1;
        if(cantidad_naves==1){
            btnNave2.setEnabled(false);
            btnNave1.setEnabled(false);
            btnNave3.setEnabled(false);
            btnNave4.setEnabled(false);
        }
      //  btnNave1.setEnabled(false);
    }//GEN-LAST:event_btnNave1ActionPerformed

    private void btnNave3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNave3ActionPerformed
        // TODO add your handling code here:
        new GetMovimiento1( this ).setVisible(true);
        //Se desabilita el boton porque solo es 1 tipo de nave por turno
        tipoNave =3;
        if(cantidad_naves==1){
            btnNave2.setEnabled(false);
            btnNave1.setEnabled(false);
            btnNave3.setEnabled(false);
            btnNave4.setEnabled(false);
        }
     //   btnNave3.setEnabled(false);
    }//GEN-LAST:event_btnNave3ActionPerformed

    private void btnNave2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNave2ActionPerformed
        // TODO add your handling code here:
        new GetMovimiento1( this ).setVisible(true);
        //Se desabilita el boton porque solo es 1 tipo de nave por turno
        tipoNave =2;
     //   btnNave2.setEnabled(false);
        if(cantidad_naves==1){
            btnNave1.setEnabled(false);
            btnNave3.setEnabled(false);
            btnNave4.setEnabled(false);
            btnNave2.setEnabled(false);
        }
    }//GEN-LAST:event_btnNave2ActionPerformed

    private void btnNave4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNave4ActionPerformed
        // TODO add your handling code here:
        new GetMovimiento1( this ).setVisible(true);
        //Se desabilita el boton porque solo es 1 tipo de nave por turno
        tipoNave =4;
        if(cantidad_naves==1){
            btnNave2.setEnabled(false);
            btnNave3.setEnabled(false);
            btnNave1.setEnabled(false);
            btnNave4.setEnabled(false);
        }
     //   btnNave4.setEnabled(false);
    }//GEN-LAST:event_btnNave4ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        try {
            HOST = JOptionPane.showInputDialog(null, "Ingrese la direccion IP:").toString();//pide la IP para conectarse
            boolean cumple = Pattern.matches("\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}", HOST);//verifica que la ip este en formato valido
            if (!cumple) {
                JOptionPane.showMessageDialog(this, "Debe Ingresar una direccion IP valida");
            } //if (HOST.isEmpty()){
            //    JOptionPane.showMessageDialog(this, "Debe Ingresar una direccion IP");}
            else {
                // Establece la conexión con el socket
                Socket cliente = new Socket(HOST, PUERTO); //se crea el socket para la conexion
                InputStream inputStream = cliente.getInputStream();//se crea un flujo de entrada
                DataInputStream flujo = new DataInputStream(inputStream); // Lee el mensaje que envia el socket
                String mensaje = flujo.readUTF(); //guardo el mensaje en una variable
                if (mensaje.equals("Exitosa")) { //si el puerto lee el mensaje de exitoso, quiere decir que la conexion fue exitosa
                    JOptionPane.showMessageDialog(this, "Conexion Exitosa"); //muestra un mensaje
                    this.mnuNuevo.setEnabled(false);//habilita el menu de nuevo juego
                    com.set(HOST, PUERTO);
                }
                System.out.println(mensaje);
                cliente.close();//cierra la conexion
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            JOptionPane.showMessageDialog(this, "Conexion Fallida");//muestra si la conxion fue fallida
            this.mnuNuevo.setEnabled(false);
        }
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void mnuSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuSalirActionPerformed
        System.exit(0);
    }//GEN-LAST:event_mnuSalirActionPerformed

    private void mnuNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuNuevoActionPerformed
        elegirJugadorServidor();
        //System.out.println(esServidor);
    }//GEN-LAST:event_mnuNuevoActionPerformed

    private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
        // TODO add your handling code here:
       /* if(nav1)
            btnNave1.setEnabled(false);
        if(nav2)
            btnNave2.setEnabled(false);
        if(nav3)
            btnNave3.setEnabled(false);
        if(nav4)
            btnNave4.setEnabled(false);*/
    }//GEN-LAST:event_formWindowGainedFocus

private void btnIniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIniciarActionPerformed
    //Si el jugador es servidor
    this.jdElegirServidor.setVisible( false );
    if( this.jrbJugadorS.isSelected() )
    {
        //Se le preugnta al jugador cuantos naves quiere utilizar
        this.asignarCantidadNaves();
        this.jPanel1.setEnabled( true );
        this.jPanel2.setEnabled( true );
        //this.jPanel1.setVisible( true );
        this.jPanel2.setVisible( true );
        esServidor = true;
        this.jMenuItem2.setVisible(false);
        this.mnuNuevo.setEnabled(false);
        servidor serv = new servidor();
        System.out.println(esServidor);
    }
    else
        esServidor = false;
        this.jMenuItem2.setVisible(true);
        this.mnuNuevo.setEnabled(false);
        System.out.println(esServidor);
    
    
}//GEN-LAST:event_btnIniciarActionPerformed

private void jrbJugadorSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbJugadorSActionPerformed
    this.jrbJugadorC.setSelected( false );
    this.jrbJugadorS.setSelected( true );
}//GEN-LAST:event_jrbJugadorSActionPerformed

private void jrbJugadorCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbJugadorCActionPerformed
    this.jrbJugadorS.setSelected( false );
    this.jrbJugadorC.setSelected( true );
}//GEN-LAST:event_jrbJugadorCActionPerformed

private void btnListoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnListoActionPerformed
    this.btnListo.setVisible( false );
    this.jLabel3.setVisible( true );
    this.lblTiempo.setVisible( true );
        
    cronometro = new Cronometro1( lblTiempo );
    cronometro.start();
}//GEN-LAST:event_btnListoActionPerformed
//Crea las acciones para los botones
private void MatrizBotonesActionPerformed(java.awt.event.ActionEvent evt){
    CharSequence p1 = evt.getSource().toString().subSequence(407, 412);
    CharSequence text="";
    for(int k=0;k<5;k++){
        if(p1.charAt(k)=='0'||p1.charAt(k)=='1'||p1.charAt(k)=='2'||p1.charAt(k)=='3'||p1.charAt(k)=='4'||p1.charAt(k)=='5'||p1.charAt(k)=='6'||p1.charAt(k)=='7'||p1.charAt(k)=='8'||p1.charAt(k)=='9')
            text=text.toString().concat(String.valueOf(p1.charAt(k)));
    }
    for (int i =0;i<intAlto;i++){
        for(int j=0;j<intAncho;j++){
            if(btnMatrizBotonesOponente[i][j].getText().equalsIgnoreCase(text.toString())){
                if(matrizCasillasOponente[i][j].getIntElemento()==1){
                    
                }
                btnMatrizBotonesOponente[i][j].setEnabled(false);
                matrizCasillasOponente[i][j].setBoolEstado(false);
                j=intAnchoBtn;
                i=intAltoBtn;
            }
        }
    }
}

//Crea el metodo del jugador actual
private void crearTablero(int alto, int ancho) {
        btnMatrizBotones = new JButton[alto][ancho];
        matrizCasillas = new claseCasilla[alto][ancho];
        for (int intFila = 0; intFila < alto; intFila++) {
            for (int intCol = 0; intCol < ancho; intCol++) {
                btnMatrizBotones[intFila][intCol] = new JButton();
                matrizCasillas[intFila][intCol]= new claseCasilla();
                btnMatrizBotones[intFila][intCol].setVisible(true);
                //btnMatrizBotones[intFila][intCol].setBounds(155 + intFila * intAnchoBtn, 35 + intCol * intAltoBtn, intAncho-1, intAltoBtn-1);
                btnMatrizBotones[intFila][intCol].setSize(intAnchoBtn+4, intAltoBtn+4);
                btnMatrizBotones[intFila][intCol].setLocation(155 + intFila * intAnchoBtn, 35 + intCol * intAltoBtn);
                getContentPane().add(btnMatrizBotones[intFila][intCol]);
                matrizCasillas[intFila][intCol].setBoolEstado(true);
                matrizCasillas[intFila][intCol].setIntElemento(0);
            }
        }
    }
//Crea el tablero del oponente
    private void crearTableroOponente(int alto, int ancho) {
        btnMatrizBotonesOponente = new JButton[alto][ancho];
        matrizCasillasOponente = new claseCasilla[alto][ancho];
        Integer intNem=0;
        for (int intFila = 0; intFila < alto; intFila++) {
            for (int intCol = 0; intCol < ancho; intCol++) {
                btnMatrizBotonesOponente[intFila][intCol] = new JButton();
                matrizCasillasOponente[intFila][intCol]= new claseCasilla();
                btnMatrizBotonesOponente[intFila][intCol].setVisible(true);
                btnMatrizBotonesOponente[intFila][intCol].setEnabled(false);
                btnMatrizBotonesOponente[intFila][intCol].setText(intNem.toString());
                intNem++;
               // btnMatrizBotonesOponente[intFila][intCol].setBounds(200+(ancho*intAnchoBtn)+ intFila * intAnchoBtn+5, 35+intCol*intAltoBtn+5, intAnchoBtn+25, intAltoBtn+25);
                btnMatrizBotonesOponente[intFila][intCol].setSize(intAnchoBtn+15, intAltoBtn+15);
                btnMatrizBotonesOponente[intFila][intCol].setLocation((200 + ancho * intAnchoBtn)+(intFila * (intAnchoBtn+10)),  35 + intCol * (intAltoBtn+10));
                getContentPane().add(btnMatrizBotonesOponente[intFila][intCol]);
                matrizCasillasOponente[intFila][intCol].setBoolEstado(true);
                matrizCasillasOponente[intFila][intCol].setIntElemento(0);
            }
        }
    }
    //---------------------------Pantalla de Inicio---------------------------//
    public void splash(){
        jw = new javax.swing.JWindow();
        JLabel img = new JLabel( new ImageIcon( this.getClass().getResource(
                "/images/splash.jpg" ) ) );
        img.setSize( 480, 300 );
        jw.add( img );
        jw.setSize( 480, 300 );
        jw.setLocationRelativeTo( null );
        jw.setVisible( true );
    }
    //------------------------------------------------------------------------//
    
    //-------Muestra el JDialog para la eleccion entre Cliente o Servidor-----//
    public void elegirJugadorServidor(){
        this.jrbJugadorS.setSelected( true );
        this.jrbJugadorC.setSelected( false );
        this.jdElegirServidor.setSize( 300, 150 );
        this.jdElegirServidor.setLocationRelativeTo( null );
        this.jdElegirServidor.setVisible( true );
        this.jdElegirServidor.setAlwaysOnTop( true );
    }
    //------------------------------------------------------------------------//
    
    //--------------------Pide cuantas naves van a utilizar-------------------//
    public void asignarCantidadNaves(){
        cantidad_naves = 0;
        String naves;
        do{
            naves = 
            JOptionPane.showInputDialog(this, "¿Cuantas naves desea colocar?", 
                    "Cantidad de Naves", JOptionPane.QUESTION_MESSAGE);
            if( naves.equals("") )
                JOptionPane.showMessageDialog(this, "Debe ingresar un valor", 
                    "Informacion", JOptionPane.INFORMATION_MESSAGE );
        }
        while( naves.equals( "" ) || naves.equals( "0" ) );
        cantidad_naves = Integer.parseInt( naves );
    }
    //------------------------------------------------------------------------//
    
    //------------------Verifica la cantidad de naves-------------------------//
    public void puedeAgregarNave(){
        cantidad_naves -= 1;
        if( cantidad_naves == 0 ){ 
            this.jPanel1.setVisible( false );
            JOptionPane.showMessageDialog( this, "A ingresado todas sus naves.", 
                    "Informacion", JOptionPane.INFORMATION_MESSAGE );
            
            //this.btnListo.setLocation( 50, 10 );
            this.btnListo.setVisible( true );
        }
    }
    //------------------------------------------------------------------------//
    
    //---------------------Agrega vida segun el tipo de nave------------------//
    public void agregarVida( int nueva_vida ){
        vida += nueva_vida;
    }
    //------------------------------------------------------------------------//
    
    //------------Quita una vida y si sigue con vida devuelve un true---------//
    public boolean quitarVida(){
        vida -= 1;
        if( vida == 0 ) return false;
        return true;
    }
    //------------------------------------------------------------------------//
    
    //-----------------Establece la cantidad de naves a utilizar--------------//
    public void setCantidadNaves( int cant ){
        cantidad_naves = cant;
    }
    //------------------------------------------------------------------------//
    
    //---------------------Obtiene la cantidad de naves a usar----------------//
    public int getCantidadNaves(){
        return cantidad_naves;
    }
    //------------------------------------------------------------------------//
    
    //-----------------------Mensaje al terminar el juego---------------------//
    public void mensajeFinJuego(){
        if( vida != 0 )
            JOptionPane.showMessageDialog(this, "¡Eres el ganador!", 
                    "Fin del Juego", JOptionPane.INFORMATION_MESSAGE );
        else
            JOptionPane.showMessageDialog(this, "Mayor suerte a la proxima, has perdido", 
                    "Fin del Juego", JOptionPane.INFORMATION_MESSAGE );
    }
    //------------------------------------------------------------------------//
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Panel().setVisible( true );
            }
        });
        
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCrear;
    private javax.swing.JButton btnIniciar;
    private javax.swing.JButton btnListo;
    private javax.swing.JButton btnNave1;
    private javax.swing.JButton btnNave2;
    private javax.swing.JButton btnNave3;
    private javax.swing.JButton btnNave4;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem2;
    public javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JDialog jdElegirServidor;
    private javax.swing.JRadioButton jrbJugadorC;
    private javax.swing.JRadioButton jrbJugadorS;
    private javax.swing.JLabel lblTiempo;
    private javax.swing.JLabel lbltab;
    private javax.swing.JLabel lbltabOp;
    private javax.swing.JMenuItem mnuNuevo;
    private javax.swing.JMenuItem mnuSalir;
    private javax.swing.JRadioButton op15;
    private javax.swing.JRadioButton op20;
    private javax.swing.JRadioButton op25;
    // End of variables declaration//GEN-END:variables
    static String HOST = ""; //este llevara la ip a la que se desea conectar
    static final int PUERTO = 9999; //este es el puerto en el que se escribira y se escuchara
    Cronometro1 cronometro;
    
    public boolean esServidor;
    JWindow jw;
    public int vida;
    public int cantidad_naves;
    private Conmunicacion com = new Conmunicacion();
}
